package com.f6.weixin.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.f6.utils.HttpClientUtil;
import com.f6.weixin.common.vo.SNSUserInfo;
import com.f6.weixin.common.vo.WeiXinOauth2Token;

public class WeixinAuthUtil {
	private static Logger logger = LoggerFactory.getLogger(WeixinAuthUtil.class);

	public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
		SNSUserInfo user = null;
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId;
		String response = HttpClientUtil.httpGetRequest(url);
		JSONObject jsonobj = JSONObject.parseObject(response);

		if (jsonobj != null) {
			try {
				user = new SNSUserInfo();
				user.setOpenId(jsonobj.getString("openid"));
				user.setNickname(jsonobj.getString("nickname"));
				user.setCity(jsonobj.getString("city"));
				user.setCountry(jsonobj.getString("country"));
				user.setHeadImgUrl(jsonobj.getString("headimgurl"));
				user.setProvince(jsonobj.getString("province"));
				user.setSex(jsonobj.getIntValue("sex"));
				user.setPrivilegeList(JSONArray.parseArray(jsonobj.getJSONArray("provilege").toJSONString(),String.class));
			} catch (Exception e) {
				user = null;
				int errorCode = jsonobj.getIntValue("errcode");
				String errorMsg = jsonobj.getString("errmsg");
				logger.error("获取网页授权凭证失败 errcode:{}  errmsg:{}", errorCode, errorMsg);
			}
		}
		return user;
	}

//	public static void getAuthCode() {
//		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID + "&redirect_uri=" + REDIRECT_URI
//				+ "&response_type=code&scope=" + SCOPE + "&state=" + STATE + "#wechat_redirect";
//	}

	public static WeiXinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + code
				+ "&grant_type=authorization_code";
		String response = HttpClientUtil.httpGetRequest(url);
		JSONObject jsonobj = JSONObject.parseObject(response);
		WeiXinOauth2Token wat = null;
		if (jsonobj != null) {
			try {
				wat = new WeiXinOauth2Token();
				wat.setAccessToken(jsonobj.getString("access_token"));
				wat.setExpiresIn(jsonobj.getIntValue("expires_in"));
				wat.setRefreshToken(jsonobj.getString("refresh_token"));
				wat.setOpenId(jsonobj.getString("openid"));
				wat.setScope(jsonobj.getString("scope"));
			} catch (Exception e) {
				wat = null;
				int errorCode = jsonobj.getIntValue("errcode");
				String errorMsg = jsonobj.getString("errmsg");
				logger.error("获取网页授权凭证失败 errcode:{}  errmsg:{}", errorCode, errorMsg);
			}
		}
		return wat;
	}

}
